package cn.com.bluemoon.daps.system.service.impl;

import cn.com.bluemoon.daps.common.domain.BaseModel;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.enums.BmStatus;
import cn.com.bluemoon.daps.system.entity.DapSystemDatasource;
import cn.com.bluemoon.daps.system.entity.DapSystemDatasourceEnvironment;
import cn.com.bluemoon.daps.system.entity.DapSystemSchema;
import cn.com.bluemoon.daps.system.mapper.DapSystemDatasourceMapper;
import cn.com.bluemoon.daps.system.mapper.DapSystemSchemaMapper;
import cn.com.bluemoon.daps.system.service.DapSystemDatasourceEnvironmentService;
import cn.com.bluemoon.daps.system.service.DapSystemDatasourceService;
import cn.com.bluemoon.daps.system.service.DapSystemSchemaService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DapSystemSchemaServiceImpl extends ServiceImpl<DapSystemSchemaMapper, DapSystemSchema>
        implements DapSystemSchemaService {

    @Autowired
    DapSystemSchemaMapper dapSystemSchemaMapper;

    @Autowired
    DapSystemDatasourceMapper dapSystemDatasourceMapper;

    @Autowired
    DapSystemDatasourceEnvironmentService environmentService;

    @Override
    public IPage<DapSystemSchema> getSchemaPage(Integer pageSize, Integer pageNum, String schemaName) {

        // 分页条件
        Page<DapSystemSchema> pages = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<DapSystemSchema> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DapSystemSchema::getBmStatus, BmStatus.ON.getCode())
                .orderByDesc(DapSystemSchema::getUpdateTime,DapSystemSchema::getCreateTime);
        if (!StringUtils.isEmpty(schemaName)){
            wrapper.like(DapSystemSchema::getSchemaName, schemaName);
        }
        return dapSystemSchemaMapper.selectPage(pages, wrapper);
    }

    @Override
    public ResultBean<String> insertSchema(DapSystemSchema dapSystemSchema) {

        // 查询是否重复
        List<DapSystemSchema> dapSystemSchemas = dapSystemSchemaMapper.selectList(new LambdaQueryWrapper<DapSystemSchema>()
                .eq(DapSystemSchema::getSchemaName, dapSystemSchema.getSchemaName())
                .eq(DapSystemSchema::getBmStatus, BmStatus.ON.getCode()));
        // 查询绑定的数据源是否存在
        String[] split = dapSystemSchema.getDatasourceIds().split(",");
        List<String> list = Arrays.asList(split);
        List<DapSystemDatasource> dapSystemDatasourceList = dapSystemDatasourceMapper.selectBatchIds(list);
        List<String> datasourceIds = dapSystemDatasourceList.stream()
                .map(DapSystemDatasource::getId).collect(Collectors.toList());
        List<String> unExist = list.stream().filter(l -> !datasourceIds.contains(l)).collect(Collectors.toList());
        List<Integer> integers = Arrays.asList(1, 2, 3, 4);
        if(!unExist.isEmpty()){
            return ResultBean.error(String.format("数据源id%s不存在",unExist));
        }
        // 环境校验
        if(!integers.contains(dapSystemSchema.getEnvironment())){
            return ResultBean.ok("所选数据源环境不存在");
        }
        // 校验数据源是否存在当前环境
        LambdaQueryWrapper<DapSystemDatasourceEnvironment> in = new LambdaQueryWrapper<DapSystemDatasourceEnvironment>()
                .eq(BaseModel::getBmStatus, BmStatus.ON.getCode()).eq(DapSystemDatasourceEnvironment::getIsInfoResource, false)
                .in(DapSystemDatasourceEnvironment::getDatasourceId, list);
        List<DapSystemDatasourceEnvironment> environments = environmentService.getBaseMapper().selectList(in);
        // 根据数据源id进行分类
        List<String> ids = Lists.newArrayList();
        Map<String, List<DapSystemDatasourceEnvironment>> map = environments.stream().collect(Collectors.groupingBy(DapSystemDatasourceEnvironment::getDatasourceId));
        for (Map.Entry<String, List<DapSystemDatasourceEnvironment>> entry : map.entrySet()) {
            List<DapSystemDatasourceEnvironment> value = entry.getValue();
            List<Integer> collect = value.stream().map(DapSystemDatasourceEnvironment::getEnvironment).collect(Collectors.toList());
            if(!collect.contains(dapSystemSchema.getEnvironment())){
                ids.add(entry.getKey());
            }
        }
        List<String> datasourceName = dapSystemDatasourceList.stream().filter(d -> ids.contains(d.getId())).map(DapSystemDatasource::getName).collect(Collectors.toList());
        if(!datasourceName.isEmpty()){
            return ResultBean.error(String.format("%s数据源不存在当前选中的环境", datasourceName));
        }
        if (dapSystemSchemas.isEmpty()){
            dapSystemSchemaMapper.insert(dapSystemSchema);
            return ResultBean.ok();
        }else {
            List<String> collect = dapSystemSchemas.stream().map(DapSystemSchema::getSchemaName).collect(Collectors.toList());
            return ResultBean.error(collect.toString()+"schema名重复");
        }
    }
}
